package org.breathe.internal;

import lombok.Setter;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
public class Sds {
    @Setter
    private byte[] bytes;
    private int length;
    private int alloc;
    private static final int SDS_MAX_ALLOC = 1024 * 1024;
    public Sds(byte[] bytes) {
        this.length = bytes.length;
        this.alloc = calculateAlloc(bytes.length);
        this.bytes = new byte[this.alloc];
        System.arraycopy(bytes, 0, this.bytes, 0, bytes.length);
    }
    private int calculateAlloc(int length) {
        if (length <= SDS_MAX_ALLOC) {
            return Math.max(length * 2, 8);
        }
        return this.length + SDS_MAX_ALLOC;
    }
    @Override
    public String toString() {
        return new String(this.bytes, StandardCharsets.UTF_8);
    }
    public int length() {
        return length;
    }
    public void clear() {
        this.length = 0;
    }
    public Sds append(byte[] extra) {
        int newLength = length + extra.length;
        if (newLength > this.alloc) {
            int newAlloc = calculateAlloc(newLength);
            byte[] newBytes = new byte[newAlloc];
            System.arraycopy(bytes, 0, newBytes, 0, length);
            bytes = newBytes;
            this.alloc = newAlloc;
            this.length = newLength;
        }
        return this;
    }
    public Sds append(String s) {
        return append(s.getBytes());
    }
    public byte[] getBytes() {
        byte[] result = new byte[length];
        System.arraycopy(bytes, 0, result, 0, length);
        return result;
    }
}
